<template>
  <el-dialog
    :model-value="visible"
    title="用户分配管理"
    width="900px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @update:model-value="handleVisibleChange"
    @close="handleClose"
  >
    <div class="user-assign-container">
      <!-- 物业公司信息 -->
      <div class="property-company-section">
        <h3>物业公司信息</h3>
        <div class="company-info">
          <div class="company-name">{{ propertyCompany?.companyName }}</div>
          <div class="company-code">编码：{{ propertyCompany?.companyCode }}</div>
        </div>
      </div>

      <!-- 用户分配区域 -->
      <div class="user-assign-section">
        <h3>用户分配</h3>
        <div class="assign-content">
          <!-- 左侧：可分配的用户 -->
          <div class="available-users">
            <h4>可分配用户</h4>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户名或姓名"
              prefix-icon="Search"
              clearable
              @input="filterAvailableUsers"
            />
            <div class="user-list">
              <el-checkbox-group v-model="selectedUsers">
                <div
                  v-for="user in filteredAvailableUsers"
                  :key="user.id"
                  class="user-item"
                >
                  <el-checkbox :value="user.id">
                    <div class="user-info">
                      <div class="user-name">{{ user.username }}</div>
                      <div class="user-real-name">{{ user.realName || '-' }}</div>
                    </div>
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </div>

          <!-- 中间：操作按钮 -->
          <div class="assign-actions">
            <el-button
              type="primary"
              :disabled="!selectedUsers.length"
              @click="assignUsers"
            >
              <el-icon><ArrowRight /></el-icon>
              分配
            </el-button>
            <el-button
              type="danger"
              :disabled="!selectedAssignedUsers.length"
              @click="unassignUsers"
            >
              <el-icon><ArrowLeft /></el-icon>
              取消分配
            </el-button>
          </div>

          <!-- 右侧：已分配的用户 -->
          <div class="assigned-users">
            <h4>已分配用户</h4>
            <div class="user-list">
              <el-checkbox-group v-model="selectedAssignedUsers">
                <div
                  v-for="user in assignedUsers"
                  :key="user.id"
                  class="user-item"
                >
                  <el-checkbox :value="user.id">
                    <div class="user-info">
                      <div class="user-name">{{ user.username }}</div>
                      <div class="user-real-name">{{ user.realName || '-' }}</div>
                      <div class="user-position">{{ user.position || '-' }}</div>
                    </div>
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存分配
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ArrowRight, ArrowLeft } from '@element-plus/icons-vue'
import { showSuccess, showError, showWarning } from '@/utils/message'
import { useUserStore } from '@/store/user'
import { hasMenuPermission } from '@/utils/permission'
import { propertyCompanyApi } from '@/api/property/propertyCompany'
import { getUserList } from '@/api/user'

// 作者：Wu.Liang
// 创建时间：2025-01-30
// 功能：物业公司用户分配管理弹窗组件

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  propertyCompany: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success', 'cancel'])

const userStore = useUserStore()

// 权限检查
const isSuperAdmin = computed(() => userStore.isAdmin())

const hasAssignPermission = computed(() => {
  return hasMenuPermission('property:company:menu')
})

// 响应式数据
const allUsers = ref([])
const assignedUsers = ref([])
const selectedUsers = ref([])
const selectedAssignedUsers = ref([])
const searchKeyword = ref('')
const saving = ref(false)

// 计算属性
const filteredAvailableUsers = computed(() => {
  if (!searchKeyword.value) {
    return allUsers.value.filter(user => 
      !assignedUsers.value.some(assigned => assigned.id === user.id)
    )
  }
  
  return allUsers.value.filter(user => {
    const isNotAssigned = !assignedUsers.value.some(assigned => assigned.id === user.id)
    const matchesSearch = user.username.includes(searchKeyword.value) || 
                         (user.realName && user.realName.includes(searchKeyword.value))
    return isNotAssigned && matchesSearch
  })
})

// 监听器
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 检查权限
    if (!hasAssignPermission.value) {
      showError('您没有用户分配权限')
      emit('update:visible', false)
      return
    }
    
    // 检查物业公司信息
    if (!props.propertyCompany) {
      showError('物业公司信息不能为空')
      emit('update:visible', false)
      return
    }
    
    initData()
  }
})

// 方法
const initData = async () => {
  try {
    await Promise.all([
      loadAllUsers(),
      loadAssignedUsers()
    ])
    resetSelection()
  } catch (error) {
    console.error('初始化数据失败:', error)
    showError('初始化数据失败')
  }
}

const loadAllUsers = async () => {
  try {
    const response = await getUserList({
      current: 1,
      size: 1000
    })
    if (response.data) {
      allUsers.value = response.data.records || []
    } else {
      showError('获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    showError('获取用户列表失败')
  }
}

const loadAssignedUsers = async () => {
  try {
    const response = await propertyCompanyApi.getAssignedUsers(props.propertyCompany.id)
    if (response.code === 200) {
      assignedUsers.value = response.data || []
    } else {
      showError(response.message || '获取已分配用户失败')
    }
  } catch (error) {
    console.error('获取已分配用户失败:', error)
    showError('获取已分配用户失败')
  }
}

const filterAvailableUsers = () => {
  // 搜索功能通过计算属性实现
}

const assignUsers = async () => {
  if (selectedUsers.value.length === 0) {
    showWarning('请选择要分配的用户')
    return
  }
  
  try {
    const response = await propertyCompanyApi.assignUsers({
      propertyCompanyId: props.propertyCompany.id,
      userIds: selectedUsers.value
    })
    
    if (response.code === 200) {
      showSuccess('用户分配成功')
      await loadAssignedUsers()
      resetSelection()
    } else {
      showError(response.message || '用户分配失败')
    }
  } catch (error) {
    console.error('用户分配失败:', error)
    showError('用户分配失败')
  }
}

const unassignUsers = async () => {
  if (selectedAssignedUsers.value.length === 0) {
    showWarning('请选择要取消分配的用户')
    return
  }
  
  try {
    const response = await propertyCompanyApi.unassignUsers({
      propertyCompanyId: props.propertyCompany.id,
      userIds: selectedAssignedUsers.value
    })
    
    if (response.code === 200) {
      showSuccess('取消分配成功')
      await loadAssignedUsers()
      resetSelection()
    } else {
      showError(response.message || '取消分配失败')
    }
  } catch (error) {
    console.error('取消分配失败:', error)
    showError('取消分配失败')
  }
}

const resetSelection = () => {
  selectedUsers.value = []
  selectedAssignedUsers.value = []
  searchKeyword.value = ''
}

const handleVisibleChange = (value) => {
  emit('update:visible', value)
}

const handleClose = () => {
  emit('cancel')
}

const handleSave = () => {
  // 保存操作已经在分配和取消分配时完成
  emit('success')
}
</script>

<style scoped>
.user-assign-container {
  padding: 20px 0;
}

.property-company-section {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.property-company-section h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #303133;
}

.company-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.company-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.company-code {
  font-size: 14px;
  color: #606266;
}

.user-assign-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #303133;
}

.assign-content {
  display: flex;
  gap: 20px;
  height: 400px;
}

.available-users,
.assigned-users {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.available-users h4,
.assigned-users h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #606266;
}

.user-list {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px;
}

.user-item {
  margin-bottom: 8px;
}

.user-item:last-child {
  margin-bottom: 0;
}

.user-info {
  margin-left: 8px;
}

.user-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 2px;
}

.user-real-name {
  font-size: 12px;
  color: #606266;
  margin-bottom: 2px;
}

.user-position {
  font-size: 12px;
  color: #909399;
}

.assign-actions {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 12px;
  padding: 0 16px;
}

.dialog-footer {
  text-align: right;
}
</style> 